﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
using IniParser;

namespace SysInfo
{
    public class TableInfo
    {
        private string dir_path = @"tables";
        /// <summary>
        /// table_info[table_name][field_name] -> DatabaseFieldNode
        /// </summary>
        private Dictionary<string, Dictionary<string, DatabaseFieldNode>> table_info;

        static TableInfo instance;

        public TableInfo() {
            table_info = new Dictionary<string, Dictionary<string, DatabaseFieldNode>>();
            Initial();
        }

        public static TableInfo GetInstance()
        {
            if (instance == null)
                instance = new TableInfo();
            return instance;
        }

        /// <summary>
        /// Return the information of all fields in this table
        /// </summary>
        /// <param name="table_name">given table name</param>
        /// <returns>list of key-value pairs, which key is databse name and value is DatabaseFieldNode</returns>
        public Dictionary<string, DatabaseFieldNode> this[string table_name]
        {
            get {
                foreach (var pair in table_info) {
                    if (pair.Key == table_name)
                        return pair.Value;
                }
                return null;
            }
        }
        private void Initial() {
            DirectoryInfo di = new DirectoryInfo(dir_path);
            string table_name;
            Dictionary<string, DatabaseFieldNode> namePairs;
            foreach (FileInfo fi in di.GetFiles()) {
                if (fi.Extension == ".ini") {

                    table_name = fi.Name.Substring(0, fi.Name.Count() - fi.Extension.Count());
                    namePairs = new Dictionary<string, DatabaseFieldNode>();

                    IniParser.FileIniDataParser parser = new FileIniDataParser();
                    IniData data = parser.LoadFile(dir_path + @"\" + fi.Name);
                    // Add name & display_name
                    foreach (KeyData nameData in data["fields"]) {
                        namePairs.Add(nameData.KeyName, new DatabaseFieldNode(nameData.KeyName, nameData.Value));
                    }
                    // Add mapping fields
                    foreach (KeyData mapData in data["maps"]) {
                        namePairs[mapData.KeyName].SetMappingTable(mapData.Value);
                    }
                    foreach (KeyData typeData in data["types"]) {
                        namePairs[typeData.KeyName].SetDataType(typeData.Value);
                    }
                    table_info.Add(table_name, namePairs);
                }
            } 
        }
    }

}
